var common = require("../../utils/common.js");
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    canIUse: false,
    loading: true,
    resObj: [],//根据接口获取的帖子详情数据
    forumid: '',//帖子id
    forumImg: [],//存取图片
    replyList: [],
    inputValue: "",
    hfcontent: '',//回复的内容
    isTiezi: true,//是不是给帖子回复
    isShowTiezi:false,
  },
  onLoad: function (options) {
    if (options.forumid) {
      this.setData({
        forumid: options.forumid,
        xcxid:options.xcxid
      })
    } 
    if (app.globalData.xcxtype.isShow == "1") {
      this.setData({
        isShowTiezi: true
      })
    } else {
      this.setData({
        isShowTiezi: false
      })
    }
    wx.setNavigationBarTitle({
      title: '论坛详情'
    });


    //进入论坛列表页，首先查询用户信息
    //需要bid:"", xcxOpenId: ''
    var that = this;
    that.setData({
      loading: true
    })
    wx.login({
      success: res => {
        if (res.code) {
          var code = res.code;
          //获取xcxOpenId;
          // 获取用户信息
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({
                  success: function (res) {
                    console.log(res.userInfo)
                    app.globalData.userInfo = res.userInfo;
                    app.globalData.isFind = true;
                    that.getOpenId(code);
                  }
                })
              } else {
                //未授权登录
                app.globalData.isFind = false;
                that.getOpenId(code);
                that.setData({
                  loading: false,
                  canIUse: true
                })
              }
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg);
          that.setData({
            loading: true
          })
        }
      }
    })
  },
  onShow: function () {
    
  },

  getOpenId: function (code) {
    var that = this;
    var xcxid;
    if (that.data.xcxid) {
      xcxid = that.data.xcxid
    } else if (app.globalData.xcxshareid) {
      xcxid = app.globalData.xcxshareid
    } else {
      xcxid = app.globalData.queryWlpXcxByParams[0].id
    }
    common.ajaxPost(
      'portal/wlpUsers/getXcxOpenId.action', {
        code: code,
        xcxId: xcxid
      },
      function (res) {
        if (res && res["result"]) {
          console.log(res);
          app.globalData.xcxOpenId = res.xcxOpenId;
          // that.findUser();
          if (app.globalData.isFind) {
            //已授权
            that.findUser();
          } else {
            //未授权
          }
        }
      }
    )
  },


  openSetting: function (e) {
    //未授权的情况
    console.log(e);
    var that = this;
    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
      return false;
    } else {
      console.log(e.detail.userInfo);
      app.globalData.userInfo = e.detail.userInfo;
      //授权时查询用户
      that.setData({
        canIUse: false,
        loading: true
      });
      that.findUser();
    }
  },


  getList: function () {
    //获取论坛详情信息
    console.log(app);
    var that = this;
    common.ajaxPost(
      '/portal/wlpForum/queryWlpForumInfo.action', {
        bid: app.globalData.bid,
        id: parseInt(that.data.forumid),
        userId: app.globalData.forumUserInf_detail.id
      },
      function (res) {
        if (res && res.resultCode == "0") {
          var resObj = res.obj;
          console.log(resObj);
          var replyList = resObj.replyList;//获取回复列表
          that.setData({
            resObj: resObj,
            replyList: replyList,
            hfcontent: '回复帖子'
          });
          var forumImg = that.data.forumImg;
          if (resObj.images && resObj.images.length > 0) {
            //图片存在并且图片数量大于0
            forumImg = (resObj.images.split(";"));
            that.setData({
              forumImg: forumImg
            })
          }
          that.setData({
             loading: false,
             canIUse: false
          })
        }
      }
    )
  },
  onReachBottom: function () {
    if (app.globalData.isGoBack == true) {
      app.globalData.isGoBack = false
    }
    this.getList();
  },

  onShareAppMessage: function (res) {
    var that=this;
    var xcxids=app.globalData.queryWlpXcxByParams[0].id

    return {
      title: '论坛详情',
      path: '/pages/index/index?type=forumDetail&bid=' + app.globalData.bid + "&isIndex=1&" + 'forumid=' + that.data.forumid + "xcxid=" + xcxids + "&lpid=" + app.globalData.lpid,
      success: function (res) {
        // 转发成功
        app.globalData.isGoBack = true;
        console.log('/pages/index/index?type=forumDetail&bid=' + app.globalData.bid + "&isIndex=1" + 'forumid=' + that.data.forumid)
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  onUnload: function () {
    app.globalData.isShareBack = true;
    app.globalData.isGoBack = true
    console.log("order退出了")
  },

  findUser: function () {
    var that = this;
    console.log(app.globalData.xcxOpenId);
    //查询用户信息
    common.ajaxPost(
      'portal/wlpUsers/queryWlpUsersForForum.action', {
        xcxOpenId: app.globalData.xcxOpenId,
        bid: app.globalData.bid
      },
      function (res) {
        if (res.resultMsg == "操作成功" && res.resultCode == "1") {
          app.globalData.forumUserInf_detail = res.data;
          //先获取列表类型
          that.getList();
        } else {
          that.modifyUser();
        }
      }
    )
  },

  modifyUser: function () {
    //保存用户信息
    var that = this;
    common.ajaxPost(
      'portal/wlpUsers/modifyUser.action', {
        userType: 2,
        headImage: app.globalData.userInfo.avatarUrl,
        name: app.globalData.userInfo.nickName,
        bid: app.globalData.bid,
        xcxOpenId: app.globalData.xcxOpenId,
      },
      function (res) {
        console.log(res);
        if (res && res["result"]) {
          if (res.resultMsg == '操作成功') {
            //添加成功，显示列表页
            app.globalData.forumUserInf_detail = res.data;
            that.setData({
              canIUse: false,
              loading: false
            });
            that.getList();
          } else {
            //添加失败，显示loading页
            that.setData({
              canIUse: false,
              loading: true
            });
          }
        }
      }
    )
  },

  //点赞
  changeIcon: function (e) {
    var that = this;
    var forumId = e.currentTarget.dataset.forumid;
    common.ajaxPost(
      '/portal/wlpForumPraise/addWlpForumPraise.action', {
        bid: app.globalData.bid,
        forumId: forumId,
        userId: app.globalData.forumUserInf_detail.id,
        userName: app.globalData.forumUserInf_detail.name,
        userHeadImg: app.globalData.forumUserInf_detail.headImage
      },
      function (res) {
        console.log(res);
        if (res.resultCode == "0") {
          wx.showToast({
            title: '点赞成功',
            icon: 'none'
          });
          var up = "resObj.hasPraise";//先用一个变量，把(info[0].gMoney)用字符串拼接起来
          var up2 = "resObj.praisenum";
          var up3 = that.data.resObj.praisenum + 1
          that.setData({
            [up]: 1,
            [up2]: up3
          })
        }
      }
    )
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  sendInf: function (e) {
    //回复帖子
    var that = this;
    if (that.data.inputValue == "") {
      wx.showToast({
        title: '回复内容不能为空',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (that.data.isTiezi) { 
      console.log(app);
      common.ajaxPost(
        '/portal/wlpForumReply/addWlpForumReply.action', {
          bid: app.globalData.bid,
          forumId: parseInt(that.data.forumid),
          userType: app.globalData.forumUserInf_detail.userType,
          userId: app.globalData.forumUserInf_detail.id,
          userName: app.globalData.forumUserInf_detail.name,
          userHeadImg: app.globalData.forumUserInf_detail.headImage,
          userPosition: app.globalData.forumUserInf_detail.position,
          replyType: 1,
          replyContent: that.data.inputValue,
        },
        function (res) {
          if (res && res.resultCode == "0") {
            that.setData({
              inputValue: '',
            })
            wx.showToast({
              title: res.resultMsg,
              icon: 'none',
              duration: 1000
            })
            that.getList();
          }
        }
      )
    }else{
      common.ajaxPost(
        '/portal/wlpForumReply/addWlpForumReply.action', {
          bid: app.globalData.bid,
          forumId: parseInt(that.data.forumid),
          userType: app.globalData.forumUserInf_detail.userType,
          userId: app.globalData.forumUserInf_detail.id,
          userName: app.globalData.forumUserInf_detail.name,
          userHeadImg: app.globalData.forumUserInf_detail.headImage,
          userPosition: app.globalData.forumUserInf_detail.position,
          replyType: 2,
          replyContent: that.data.inputValue,

          srcReplyId:that.data.sid,
          srcUserType: that.data.susertype,
          srcUserId: that.data.suserid,
          srcUserName: that.data.sname,
          srcUserHeadImg: that.data.suserheadimg,
          srcUserPosition: that.data.suserposition
        },
        function (res) {
          if (res && res.resultCode == "0") {
            that.setData({
              inputValue: '',
            })
            wx.showToast({
              title: res.resultMsg,
              icon: 'none',
              duration: 1000
            })
            that.getList();
          }
        }
      )
    }
  },

  sendOwn: function (e) {
    //回复帖子
    var sname = e.currentTarget.dataset.name;
    var sid = e.currentTarget.dataset.id;
    var that = this;
    that.setData({
      hfcontent: '回复帖子',
      inputValue: '',
      isTiezi:true
    })
  },

  sendtoOther: function (e) {
    //回复给本人
    var sname = e.currentTarget.dataset.name;
    var sid = e.currentTarget.dataset.id;
    var suserid = e.currentTarget.dataset.userid;
    var susertype = e.currentTarget.dataset.usertype;
    var suserheadimg = e.currentTarget.dataset.userheadimg;
    var suserposition = e.currentTarget.dataset.userposition;

    var that = this;
    that.setData({
      hfcontent: '回复' + sname,
      inputValue: '',
      isTiezi: false,
      sname: sname,
      sid: sid,
      suserid: suserid,
      susertype: susertype,
      suserheadimg: suserheadimg,
      suserposition: suserposition
    })
  },

  // 预览图片  
  previewImg: function (e) {     //获取当前图片的下标  
    var index = e.currentTarget.dataset.index;     //所有图片   
    var imgs = this.data.resObj.images.split(";");
    console.log(imgs)
    wx.previewImage({     //当前显示图片     
      current: imgs[index],     //所有图片     
      urls: imgs
    })
  }
})
